/*
 * Created on Feb 21, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.corpus;

import java.io.File;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.shared.ReificationStyle;

/**
 * @author dfhuynh
 */
public class DerbyConnector implements Connector {
	/* (non-Javadoc)
	 * @see edu.mit.simile.corpus.IJdbcConnector#connect(java.util.Properties, java.lang.String)
	 */
	public Corpus connect(Properties properties, String corpusURI) {
		return new DerbyCorpus(
			corpusURI, new File(properties.getProperty("directory")));
	}
}

class DerbyCorpus extends Corpus {
	static private Logger s_logger = Logger.getLogger(DerbyCorpus.class);

	protected File		m_baseDir;
	protected ModelMaker	m_modelMaker;

	public DerbyCorpus(String corpusURI, File baseDir) {
		super(corpusURI);

		m_baseDir = baseDir;
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.Corpus#dispose()
	 */
	public void dispose() {
		if (m_initialized) {
			if (m_modelMaker != null) {
				m_modelMaker.close();
				m_modelMaker = null;
			}

			super.dispose();
		}
	}

	protected void createModel() {
		if (m_model != null) {
			return;
		}

		try {
            // (SM): Works around ISSUE-1 in Derby about a bug in Java NIO for MacosX
            System.setProperty("derby.storage.fileSyncTransactionLog","true");

			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

            // FIXME(SM): make sure that we create the database if it's not already there
			String path = m_baseDir.getCanonicalPath();
			String url = "jdbc:derby:directory:" + path.replace('\\', '/') + ";create=true";

			s_logger.info("Connecting to derby DB at " + url);

			m_modelMaker = ModelFactory.createModelRDBMaker(
				new DBConnection(url, "test", "", "Derby"),
				ReificationStyle.Standard
			);

			m_model = m_modelMaker.createModel("default");
		} catch (Exception e) {
			s_logger.error(e);
			throw new InternalError(
				"Failed to create Derby model on file " +
					m_baseDir.getAbsolutePath());
		}
	}
}
